 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=229 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Provide an uncaught exception handler
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Provide an uncaught exception handler</div>

<div class='main-body'>
 
<br>In Java programs, what happens when an uncaught <a href='http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html'>RuntimeException</a> is thrown, but is not handled by your program?
In the simplest Java programs run from the console and executed in a single thread, the default behavior is to :
<ul>
 <li>print a stack trace to the console
 <li>terminate the thread (and thus terminate the program itself)
</ul>

<P>There are two common kinds of programs where the above behavior is <em>not</em> in effect:
<ul>
 <li>programs running in a servlet container
 <li>Swing applications
</ul>

<P>In Swing applications, the default behavior still prints the stack trace to the console, but the Event Dispatch Thread (the main Swing thread) is not terminated.
The Event Dispatch Thread always remains alive, in spite of any <tt>RuntimeException</tt>s thrown by your program.

<P>However, simply printing a stack trace to the console in a Swing application is not very informative for the average end user. 
Instead, you should likely override Java's default handling of uncaught exceptions.
The benefits are:
<ul>
 <li>the end user is kept informed of problems more effectively
 <li>new behavior can be added, such as logging or sending emails to support staff
</ul>

<P>If you are using JDK 5+, then you may define your own 
<a href='http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.html'>UncaughtExceptionHandler</a>.
Eric Burke has collected <a href='http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/'>some good advice</a> for implementing such a handler.

<P>In JDK 1.4, the simplest way of overriding the default handler for uncaught exceptions is to use the following undocumented feature:
 <ul>
  <li>create a class with a no-argument constructor
  <li>add to it a method <tt>public void handle(Throwable aThrowable){...}</tt>
  <li>upon startup, add a <a href='http://java.sun.com/javase/6/docs/api/java/lang/System.html'>System</a> property named <tt>'sun.awt.exception.handler'</tt>, whose value is 
   the fully qualified class name of this new handler class
 </ul> 

<P><b>Example</b>
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.movies.exception;

<span class='keyword'>import</span> hirondelle.movies.util.Util;
<span class='keyword'>import</span> hirondelle.movies.util.ui.UiUtil;

<span class='keyword'>import</span> java.io.PrintWriter;
<span class='keyword'>import</span> java.io.StringWriter;
<span class='keyword'>import</span> java.io.Writer;
<span class='keyword'>import</span> java.util.logging.Logger;
<span class='keyword'>import</span> javax.swing.JOptionPane;

<span class='comment'>/**
 Custom handler for uncaught exceptions.
 
 &lt;P&gt;By default, a Swing app will handle uncaught exceptions simply by 
  printing a stack trace to {@link System#err}. However, the end user sees 
  nothing happen. This class addresses that problem, by showing the end user a 
  simple error message in a modal dialog. (The dialog's owner is the 
  currently active frame.)
  
 &lt;P&gt;In JDK1.4, the simplest way of overriding the default handler for uncaught 
 exceptions is to use the following undocumented feature :
 &lt;ul&gt;
   &lt;li&gt;create a class with a no-argument constructor
   &lt;li&gt;add to it a method :&lt;tt&gt;public void handle(Throwable aThrowable){...}&lt;/tt&gt;
   &lt;li&gt;upon startup, add a {@link System} property named 
   &lt;tt&gt;'sun.awt.exception.handler'&lt;/tt&gt;, 
   whose value is the fully qualified class name of this new handler class
   &lt;/ul&gt; 
 
 The above technique is used by this class. 
 
 &lt;P&gt;Other alternative methods include :
 &lt;ul&gt;
   &lt;li&gt;create a custom {@link java.util.logging.Handler}, and attach it to your 
    application's loggers
   &lt;li&gt;override 
   {@link ThreadGroup#uncaughtException(java.lang.Thread, java.lang.Throwable)}
   &lt;li&gt;use later versions of Java, which provides an API related to this problem
  &lt;/ul&gt; 
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ExceptionHandler {

  <span class='comment'>/**
   No-argument constructor.
  This class must have a no-arg constructor (see class comment).
  */</span>
  <span class='keyword'>public</span> ExceptionHandler(){
    <span class='comment'>//empty
</span>  }
  
  <span class='comment'>/** 
   Custom handler for uncaught exceptions.
   
   &lt;P&gt;Displays a simple model dialog to the user, showing that an error has occured.  
   The text of the error includes {@link Throwable#toString()}.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> handle(Throwable aThrowable){
    fLogger.severe(getStackTrace(aThrowable));
    JOptionPane.showMessageDialog(
      UiUtil.getActiveFrame(), <span class='literal'>"Error: "</span> + aThrowable.toString(), 
      <span class='literal'>"Error"</span>, JOptionPane.ERROR_MESSAGE
    );
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Logger fLogger = Util.getLogger(ExceptionHandler.<span class='keyword'>class</span>);
  
  <span class='keyword'>private</span> String getStackTrace(Throwable aThrowable) {
    <span class='keyword'>final</span> Writer result = <span class='keyword'>new</span> StringWriter();
    <span class='keyword'>final</span> PrintWriter printWriter = <span class='keyword'>new</span> PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    <span class='keyword'>return</span> result.toString();
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction5ab4-2.html?Id=78'>Stack trace as String</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='229'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=229 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
